package ml.kupin.search.controller;

import ml.kupin.search.service.SearchService;
import ml.kupin.common.vo.SearchResult;
import ml.kupin.common.vo.IndexItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 商品搜索Controller
 * Created by 小柯(Allen Kerr) on 17.5.2 21:59.
 */
@Controller
public class SearchController {

    @Autowired
    private SearchService searchService;

    @Value("${SEARCH_RESULT_ROWS}")
    private Integer SEARCH_RESULT_ROWS;

    //使用配置文件填写Tomcat的默认编码格式
    @Value("${TOMCAT_DEFAULT_CHARSET}")
    private String TOMCAT_DEFAULT_CHARSET;

    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public String search(String keyword, @RequestParam(defaultValue = "1") Integer page, Model model) throws Exception {
        //如果keyword为空，即输入框没有内容，直接返回逻辑视图
        if (keyword == null) return "search";

        //keyword不为空，执行搜索
        //去掉keyword前后的空格
        keyword = keyword.trim();
        //解决get请求乱码问题
        keyword = new String(keyword.getBytes(TOMCAT_DEFAULT_CHARSET), "utf-8");
        //调用service查询
        SearchResult<IndexItem> searchResult = searchService.search(keyword, page, SEARCH_RESULT_ROWS);
        //向页面传递数据
        model.addAttribute("query", keyword);
        model.addAttribute("searchResult", searchResult);
        //返回逻辑视图
        return "search";
    }

}
